import pyperclip
import win32gui
import win32con
import os
import sys
from openpyxl import load_workbook
from openpyxl import Workbook

from pykeyboard import PyKeyboard
import time
#使用 adobe打开 pdf，ctrl + a ，ctrl + c
#关闭指定 pdf
import re
wnd =0

def wait_wd_mh(wdn):
    """等待窗口出现，成功True，失败False，最长等待50秒"""
    print("waiting window " + str(wdn))
    for i in range(1,10,1):
        time.sleep(1)
        if find_wd_mh(wdn) == True:
            return True
        else:
            print("waiting window " + str( wdn)  ,  str(i))

    return False

def find_wd_mh(wndtitle):
    ''' 用模糊发查找窗口,特点是其中包含 * '''
    #Business Workplace of Minghai Xu PC1 (1)
    res1=""
    res2=""
    global wnd
    wnd = 0
    hWndList = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
    for hwnd in hWndList:
        title = win32gui.GetWindowText(hwnd)
        #res1= re.findall(wndtitle , title,re.S)
        res1 = re.findall(wndtitle, title)
        if len(res1)>0:
            print(title, "\n", hwnd)
            res1=title
            wnd=hwnd
    if wnd != 0 :
        return True
    else:
        return False
def show_window(hwnd):
    ''' 显示窗口 便于点击'''
    #win32gui.SetForegroundWindow(hwnd)
    #置顶的问题是会遮挡其他窗口,所以尝试其他
    win32gui.ShowWindow(hwnd,8)
def Edge_zero(hwnd):
    show_window(hwnd)
    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 1920, 1000, 0)
    win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, 0, 0, 1920, 1000, 0)
    show_window(hwnd)
    return hwnd
def list_wd():
    hWndList = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
    for hwnd in hWndList:
        title = win32gui.GetWindowText(hwnd)
        print(title, "\n",hwnd)
    return hWndList
def open_copy_pdf():
    pass
    #adobe 打开pdf，全选复制
def get_pdf_txt(filepath):
    txt1=[]
    os.startfile(filepath)
    time.sleep(1)
    time.sleep(2)
    time.sleep(1)
    find_wd_mh(r"(.)Acrobat Reader DC")
    if wnd == 0:
        wait_wd_mh( r"(.)Acrobat Reader DC" )
    Edge_zero(wnd)
    kb = PyKeyboard()
    txt_lastpage=""
    txt_curpage = ""

    for i in range(1,100):
        #最多100页

        time.sleep(1)
        kb.press_key(kb.control_key)
        kb.press_key("a")
        kb.release_key("a")
        kb.release_key(kb.control_key)
        time.sleep(1)
        kb.press_key(kb.control_key)
        kb.press_key("c")
        kb.release_key("c")
        kb.release_key(kb.control_key)
        time.sleep(1)
        txt_curpage  = pyperclip.paste()
        time.sleep(1)

        if txt_lastpage == txt_curpage :
            break
        else:
            txt1.append( txt_curpage)
            txt_lastpage =txt_curpage
            #volume_down_key
            #kb.press_key(kb.page_down_key)
            #kb.release_key(kb.page_down_key)

            kb.press_key(kb.right_key )
            kb.release_key(kb.right_key)
            #kb.press_key(kb.down_key )
            #kb.release_key(kb.down_key)



    kb.press_key(kb.alt_key)
    kb.press_key(kb.function_keys[4])
    kb.release_key(kb.function_keys[4])
    kb.release_key(kb.alt_key)
    time.sleep(1)

    with  open( filepath + ".txt", 'w', encoding='utf-8') as f:
        for xx in txt1:
            f.write(xx)
            f.write( "\n" + "*" * 100 + "\n" + " PAGE END " + "\n" + "*" * 100 + "\n"  )
        f.close()
    return txt1

def read_txt_xlsx_1(ddcc1 ,fln):
    #加载pdf
    tbhead = {
        'Pos.Nr Menge Einhei Benennung Benennung 2 Teilenummer Herst.-Bezeichnung Hersteller Artikel-Nr. Bem',
        'Pos.Nr MengeEinhe Benennung Benennung 2 Teilenummer Herst.-Bezeichnung Hersteller Artikel-Nr Bem',
        'pos.-no quant unit description description 2 part no. designation by producer producer order no. note',
        'Pos.-Nr. Menge Einheit Benennung Benennung 2 Teilenummer Herst.-Bezeichnung Hersteller Artikel-Nr. Bem.',
        'pos.-no. quant. unit description description 2 part no. designation by producer producer order no. note',
        'Pos. - Nr.Menge Einheit Benennung Benennung 2 Teilenummer Herst. - Bezeichnung Hersteller Artikel - Nr.Bem.',
        'pos.-no. quant. unit description description 2 part no. designation by',
        'Pos. Material Menge Preis(EUR) Preiseinheit Betrag(EUR)',


    }
    wb2 = Workbook()
    ws_insert = wb2.active
    ws_insert.cell(1, 1).value = "PDF_FILE"
    ws_insert.cell(1, 2).value = "PAGE_N"
    i=1
    i_last=1
    b_start=False
    pagen=0
    filen= 0

    for x1 in ddcc1.keys():
        filen=filen+1
        pagen=0
        for pg in ddcc1[x1]:
            pagen=pagen+1
            #当前行数量
            i_last=i_last+1
            txt_row = pg.split("\r\n")
            print("XX")
            kklast = 0
            for xxx in txt_row:
                kklast = kklast+1

                if xxx in tbhead:
                    b_start =True
                    kklast = 0

                if b_start :
                    if len(xxx)<2 and kklast > 3:
                        b_start=False
                        kklast = 0
                    #用空格炸开,追加到尾部
                    tp1 = xxx.split(" ")
                    new_row =[x1,str(filen) + "_" + str(pagen)]
                    j=0
                    for x3 in tp1:
                        j=j+1
                        new_row.append(x3)

                    #ws_insert.append([x1,pagen,enumerate(tp1)])
                    print(   str(new_row)  )
                    if b_start:
                        ws_insert.append (new_row)
    wb2.save(fln)
    wb2.close()



if __name__ == "__main__":
    str1='''
    功能:将程序所在文件夹中的,pdf文件逐个打开,并复制其中文本,最后生成,文件夹名称命名的.xlsx文件.
    '''
    print(str1)
    ddcc1={}

    str1= input("任意键继续")


    if os.path.exists(str1) == False:
        dirname,filename=os.path.split(os.path.abspath(sys.argv[0]))
    else:
        dirname=str1
    for root,dirs,files in os.walk(dirname):
        for fl in files:
            x2=os.path.splitext(fl)[1]
            if x2 == ".pdf":
                text1=get_pdf_txt(os.path.join(root,fl))
                #创建txt文件
                ddcc1[fl]=text1
        #仅仅根目录
        break

    #预处理 里面的字符,并将其存入 xlsx 中
    read_txt_xlsx_1(ddcc1,os.path.join(dirname,"PDF_TO_EXCEL.xlsx"))

